const app = getApp()

function compress(img, context, callBack) {
	wx.getImageInfo({
		src: img,
		success: function(res) {
			var ctx = wx.createCanvasContext('photo_canvas');
			var ratio = 2;
			var canvasWidth = res.width
			var canvasHeight = res.height;	
			//比例控制在750/1366之间
			if (res.width > res.height) {
				canvasHeight = res.height * (750 / res.width)
				canvasWidth = 750
			} else if (res.height > res.width) {
				canvasWidth = res.width * (1366 / res.height)
				canvasHeight = 1366
			} else {
				while (canvasWidth > 750 || canvasHeight > 1336) {
					//比例取整
					canvasWidth = Math.trunc(res.width / ratio)
					canvasHeight = Math.trunc(res.height / ratio)
					ratio++;
				}
			}			
			context.setData({
				canvasWidth: canvasWidth,
				canvasHeight: canvasHeight
			}) //设置canvas尺寸
			ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight) //将图片填充在canvas上
			ctx.draw()
			//下载canvas图片
			setTimeout(function() {
				wx.canvasToTempFilePath({
					canvasId: 'photo_canvas',
					success: function(res) {
						//回调生成结束后的方法
						callBack(res.tempFilePath)
						//return res.tempFilePath												
					},
					fail: function(error) {
						console.log(error)
					}
				})
			}, 100)
		},
		fail: function(error) {
			console.log(error)
		}
	})
}

module.exports = {
	compress: compress
}
